package utils;

import utils.node.ChatNode;
import gui.display.ChatDisplay;

/**
 *
 */
public abstract class Chat
{
    private String name_;
    private final ServerConnection server_;
    protected final ChatDisplay display_ = new ChatDisplay( this );
    private final ChatNode node_ = new ChatNode(this);

    public Chat( final String name, final ServerConnection server )
    {
        name_ = name;
        server_ = server;
    }

    public final void nick( final String nick )
    {
        write( "NICK " + nick + "\n" );
    }

    public final void emote( final String s )
    {
        write( "PRIVMSG " + getName() + " :\001ACTION " + s + "\001\n" );
    }

    public final void privmsg( final String s )
    {
        write( "PRIVMSG " + getName() + " :" + s + "\n" );
    }

    /**
     * Returns the topic of the chat.
     */
    public void topic()
    {
        server_.write( "TOPIC " + getName() );
    }
    
    public void topic( final String newTopic )
    {
        server_.write( "TOPIC "
                + getName()
                + " :"
                + (newTopic == null ? "" : newTopic) );
    }
    
    public void join( final String channel )
    {
        server_.write( "JOIN " + channel + "\n" );
    }
    
    public abstract void part();

    protected abstract void handleCommand( String command );
    
    protected void removeFromServer()
    {
        server_.removeChat( this );
    }

    public final void handleInput( final String input )
    {
        if( input.startsWith( "/" ) )
            handleCommand( input );
        else
        {
            privmsg( input );
            userPrint( input );
        }
    }
    
    public final ChatDisplay getDisplay()
    {
        return display_;
    }

    public final void userPrint( String message )
    {
        display_.userPrint( message );
    }

    public final void print( String message )
    {
        if( IRCParser.isCommandMessage( message ) && IRCParser.getCommand( message ).equals( "MODE" ) )
            write( "NAMES " + getName() );
        display_.print( message );
    }

    protected final void write( String s )
    {
        server_.write( s );
    }

    public final String getCurrentNick()
    {
        return server_.getCurrentNick();
    }

    public final String getName()
    {
        return name_;
    }

    public final void setName( final String name )
    {
        name_ = name;
    }
    
    public final ChatNode getNode()
    {
        return node_;
    }
}
